import { defineStore } from "pinia";
import { fetchProducts, verifyStock, addToCart } from "../api/catalog";
import { products as fallbackProducts } from "../data/products";

const fallbackImage =
  "https://images.unsplash.com/photo-1582719478250-c89cae4dc85b?auto=format&fit=crop&w=600&q=80";

const buildTags = item => {
  const tags = [];
  const stock = Number(item.default_stock ?? item.stock ?? 0);
  if (stock > 0) tags.push("现货");
  if (item.brand?.name) tags.push(item.brand.name);
  if (item.origin_country) tags.push(item.origin_country);
  return tags.slice(0, 3);
};

const mapProduct = item => {
  if (!item) return null;
  const brand = item.brand?.name || item.brand_name || item.brand || "";

  return {
    id: item.id || item.product_id || item.prod_id || Math.random(),
    name: item.title || item.name || "未命名商品",
    model: item.model || item.sku_code || "-",
    brand,
    origin: item.origin_country || item.origin || "按需核实",
    warehouse:
      item.region?.name || item.warehouse || item.storage_name || "平台仓配",
    price: Number(item.default_price ?? item.price ?? 0),
    stock: Number(item.default_stock ?? item.stock ?? 0),
    leadTime: item.lead_time || item.leadTime || "请核实交期",
    seller_org_id: item.seller_org_id || null,
    seller_user_id: item.seller_user_id || null,
    image: item.cover_image || item.image || fallbackImage,
    tags: item.tags || buildTags(item)
  };
};

const mapFallbackProducts = () => fallbackProducts.map(mapProduct).filter(Boolean);

const filterLocal = (items, filters) => {
  const keyword = filters.keyword?.toLowerCase() || "";
  return items.filter(item => {
    const keywordMatch = keyword
      ? item.name.toLowerCase().includes(keyword) ||
        item.model.toLowerCase().includes(keyword) ||
        item.brand.toLowerCase().includes(keyword)
      : true;
    const brandMatch = filters.brand ? item.brand === filters.brand : true;
    const originMatch = filters.origin ? item.origin === filters.origin : true;
    const warehouseMatch = filters.warehouse
      ? item.warehouse === filters.warehouse
      : true;
    return keywordMatch && brandMatch && originMatch && warehouseMatch;
  });
};

export const useCatalogStore = defineStore("catalog", {
  state: () => ({
    list: [],
    total: 0,
    loading: false,
    filter: {
      keyword: "",
      brand: "",
      origin: "",
      warehouse: "",
      page: 1,
      page_size: 12
    },
    error: null
  }),
  getters: {
    brandOptions: state => {
      const fromList = new Set(state.list.map(item => item.brand).filter(Boolean));
      mapFallbackProducts().forEach(item => fromList.add(item.brand));
      return Array.from(fromList);
    },
    originOptions: state => {
      const fromList = new Set(state.list.map(item => item.origin).filter(Boolean));
      mapFallbackProducts().forEach(item => fromList.add(item.origin));
      return Array.from(fromList);
    },
    warehouseOptions: state => {
      const fromList = new Set(
        state.list.map(item => item.warehouse).filter(Boolean)
      );
      mapFallbackProducts().forEach(item => fromList.add(item.warehouse));
      return Array.from(fromList);
    }
  },
  actions: {
    applyFallback(filters = {}) {
      const fallback = filterLocal(mapFallbackProducts(), filters);
      this.list = fallback;
      this.total = fallback.length;
    },
    async loadList(override = {}) {
      this.loading = true;
      this.error = null;
      const merged = { ...this.filter, ...override };
      try {
        const query = {
          page: merged.page,
          page_size: merged.page_size,
          keyword: merged.keyword || undefined,
          status: 1,
          audit_status: 1
        };
        const { data } = await fetchProducts(query);
        const payload = data?.data || data || {};
        const sourceList = payload.list || payload.items || payload.data || [];
        const mapped = sourceList.map(mapProduct).filter(Boolean);
        const filtered = filterLocal(mapped, merged);
        this.list = filtered;
        this.total = payload.total || filtered.length;
        this.filter = merged;
      } catch (error) {
        this.error = error.message || "商品加载失败";
        this.applyFallback(merged);
        throw error;
      } finally {
        this.loading = false;
      }
    },
    async addCart(product, qty = 1) {
      if (!product?.id) {
        throw new Error("缺少商品ID，无法加入购物车");
      }
      const payload = {
        product_id: product.id,
        qty,
        remark: product.name,
        source_type: "buyer",
        channel: "web"
      };
      const { data } = await addToCart(payload);
      return data?.data || data;
    },
    async requestVerify(product, qty = 1) {
      const cart = await this.addCart(product, qty);
      const cartId = cart?.id;
      if (!cartId) {
        throw new Error("购物车创建失败，无法发起核实");
      }
      const { data } = await verifyStock(cartId, {
        buyer_qty: qty,
        buyer_remark: `请确认型号 ${product.model}`
      });
      return data?.data || data;
    },
    setFilter(partial) {
      this.filter = { ...this.filter, ...partial };
    }
  }
});
